/**
 * @date   2011-5-10
 * @author tianye
 */
package cn.edu.dlut.WingGame.GUI;

import android.view.MotionEvent;
import cn.edu.dlut.WingGame.BaseType.ObjectState;
import cn.edu.dlut.WingGame.Graphic.GLTexture;
import cn.edu.dlut.WingGame.IOsystem.TouchListener;
import cn.edu.dlut.WingGame.IOsystem.WingTouch;
import cn.edu.dlut.WingGame.Object.WingObject;

public class WingBitmapButton extends WingObject implements TouchListener {
	protected boolean oldFlag = false;
	protected int delay = 0;
	protected boolean isActive = false;
	protected float x = 0;
	protected float y = 0;
	protected float width = 100;
	protected float height = 30;
	GLTexture normalPic;
	GLTexture activePic;

	public WingBitmapButton() {
		WingTouch.addTouchListener(this);
	}

	public WingBitmapButton(String name) {
		super(name);
		WingTouch.addTouchListener(this);
	}

	public void set(float x, float y) {
		this.x = x;
		this.y = y;
	}

	public void set(float x, float y, float width, float height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	public void setBitmap(String normal, String active) {
		normalPic = new GLTexture();
		normalPic.creatTexture(normal);
		activePic = new GLTexture();
		activePic.creatTexture(active);

	}

	public void setButtonState(boolean flag) {
		isActive = flag;
	}

	public boolean getButtonState() {
		boolean tmp = isActive;
		if (isActive)
			oldFlag = false;
		isActive = false;
		return tmp;
	}

	@Override
	public void render() {
		if (delay == 2) {
			isActive = oldFlag;
			delay++;
		} else if (delay < 2)
			delay++;

		if (oldFlag)
			activePic.draw(x, y, width, height);
		else
			normalPic.draw(x, y, width, height);

	}

	@Override
	public void update() {
		if (mState == ObjectState.died)
			WingTouch.delTouchListener(mID);

	}

	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if ((event.getX() > x) && (event.getX() < x + width)
					&& (event.getY() > y) && (event.getY() < y + height)) {
				oldFlag = true;
				delay = 0;
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			oldFlag = false;
			delay = 0;
		}
		return false;
	}
}
